<?php
require_once ('Controller/Admin/Common.inc.php');
require_once ('View/Result.inc.php');
require_once ('Model/CircleModel.inc.php');
require_once ('Model/DeviceModel.inc.php');
require_once ('Model/DeviceToCircleModel.inc.php');
final class Controller extends common {
//	private $Loader;
	private $CircleModel;
	private $DeviceModel;
	private $DeviceToCircleModel;
	private $diaplayrows = 20;
	public function execude () {
		$this->CircleModel = new CircleModel ($this->mysql);
		$this->DeviceModel = new DeviceModel ($this->mysql);
		$this->DeviceToCircleModel = new DeviceToCircleModel ($this->mysql);
		$trace = debug_backtrace ();
		if (isset ($trace[1])) {
			$this->Loader = $trace[1]['object'];
		}
		if ($this->checklogin ()) {
			if (array_key_exists ('action', $_REQUEST)) {
				switch ($_REQUEST['action']) {
					case 'circleinfo':
						$this->devicelistPage ();
						break;
					case 'addmapping':
						$this->addMappingPage ();
						break;
					case 'deldevice':
						$this->deldevicePage ();
						break;
#					case 'delete':
#						$this->deletePage ();
#						break;
					case 'post':
						$this->wlecome(11);
					default:
						$this->listPage ();
						break;
				}
			} else {
				$this->listPage ();
			}
		}
	}

	private function deldevicePage () {
		if (array_key_exists ('id', $_REQUEST) && ctype_digit ($_REQUEST['id']) && array_key_exists ('cdid', $_REQUEST) && ctype_digit ($_REQUEST['cdid'])) {
			if ($this->DeviceToCircleModel->DelDeviceToCircle ($_REQUEST['cdid'])) {
				$this->template->addWarningMesage ('Delete Successful');
			} else {
				$this->template->addWarningMesage ('Record not exists');
			}
		} else {
			$this->template->addWarningMesage ('wrong parameter');
		}
		$this->devicelistPage ();
	}

	private function devicelistPage () {
		if (array_key_exists ('id', $_REQUEST) && ctype_digit ($_REQUEST['id']) && ($CircleInfo = $this->CircleModel->CheckCircleItemExist ($_REQUEST['id'])) != NULL) {
#			print_r ($CircleInfo);
#			print_r ($this->DeviceToCircleModel->GetDevicesByCircle ($_REQUEST['id']));

			$circleinfotemplate = new template ();
			$circleinfotemplate->load ('html/CircleManagerDeviceInfo.html');
			$circleinfo = $circleinfotemplate->dom->documentElement;
			$circleinfo = $this->template->dom->importNode ($circleinfo, true);


			$addMappingButton = $this->template->query ('div/input[@id="addMappingButton"]', $circleinfo)->item (0);
			$addMappingButton->setAttribute ('onClick', sprintf ('javascript:document.location.href="?module=%s&action=addmapping&id=%d";', $this->Loader->module, $_REQUEST['id']));

			$circleinfoitem = $this->template->query ('table/tbody[@id="circleinfo"]', $circleinfo)->item (0);

			$node = $this->template->query ('tr/td[@id="circle_name"]', $circleinfoitem)->item (0);
			$node->nodeValue = htmlspecialchars ($CircleInfo[$this->CircleModel->nameRowName]);

			$node = $this->template->query ('tr/td[@id="Devices_Count"]', $circleinfoitem)->item (0);
			$Count = $this->DeviceToCircleModel->GetDevicesByCircleCount ($CircleInfo[$this->CircleModel->idRowName]);
			$node->nodeValue = htmlspecialchars ($Count);

			$node = $this->template->query ('table/tr/td/table/tbody[@id="devicelistitem"]', $circleinfo)->item (0);
			$circlelist = $node->parentNode;
			if ($Count > 0) {
				$this->DeviceModel = new DeviceModel ($this->mysql);
				$circlelistitem = $node;
				$circlelist->removeChild ($node);
				foreach ($this->DeviceToCircleModel->GetDevicesByCircle ($_REQUEST['id']) as $CircleToDeviceItem) {
					$item = $circlelistitem->cloneNode (true);
					$DeviceItem = $this->DeviceModel->CheckDeviceItemExistByID ($CircleToDeviceItem[$this->DeviceToCircleModel->deviceIDRowName]);

					$node = $this->template->query ('tr/td[@id="Device_ID"]', $item)->item (0);
					$node->nodeValue = htmlspecialchars ($DeviceItem[$this->DeviceModel->idRowName]);

					$node = $this->template->query ('tr/td[@id="IMEI"]', $item)->item (0);
					$node->nodeValue = htmlspecialchars ($DeviceItem[$this->DeviceModel->imeiRowName]);

					$node = $this->template->query ('tr/td[@id="Circles_Count"]', $item)->item (0);
					$Count = $this->DeviceToCircleModel->GetCirclesByDeviceCount ($DeviceItem[$this->DeviceModel->idRowName]);
					$node->nodeValue = htmlspecialchars ($Count);

					$node = $this->template->query ('tr/td[@id="DeviceToCircle_StartDateTime"]', $item)->item (0);
					$node->nodeValue = htmlspecialchars ($CircleToDeviceItem[$this->DeviceToCircleModel->startDateTimeRowName]);

					$node = $this->template->query ('tr/td[@id="DeviceToCircle_EndDateTime"]', $item)->item (0);
					$node->nodeValue = htmlspecialchars ($CircleToDeviceItem[$this->DeviceToCircleModel->endDateTimeRowName]);

					$node = $this->template->query ('tr/td[@id="Device_Info"]/a', $item)->item (0);
					$node->setAttribute ('href', sprintf ('?module=%s&action=deviceinfo&id=%d', 'DeviceManager', $DeviceItem[$this->DeviceModel->idRowName]));

					$node = $this->template->query ('tr/td[@id="DeviceToCircle_Delete"]/a', $item)->item (0);
					$node->setAttribute ('href', sprintf ('?module=%s&action=deldevice&id=%d&cdid=%d', $this->Loader->module, $_REQUEST['id'], $CircleToDeviceItem[$this->DeviceToCircleModel->idRowName]));

					$circlelist->appendChild ($item);
				}
			} else {
				$circlelist->parentNode->parentNode->parentNode->removeChild ($circlelist->parentNode->parentNode);
			}
			$this->template->content->appendChild ($circleinfo);
		} else {
			$this->template->addWarningMesage ('no record here');
			$this->listPage ();
		}
	}

	private function NaddMappingPage ($CircleInfo, $id, $Device_ID = '', $StartDateTime = '', $EndDateTime = '') {
		$circleaddmappingtemplate = new template ();
		$circleaddmappingtemplate->load ('html/CircleManagerAddMapping.html');
		$circleaddmapping = $circleaddmappingtemplate->dom->documentElement;
		$circleaddmapping = $this->template->dom->importNode ($circleaddmapping, true);
		$circleaddmapping->setAttribute ('action', sprintf ('?module=%s&action=addmapping&id=%d', $this->Loader->module, $id));
		$circleinfoitem = $this->template->query ('table/tbody[@id="circleinfo"]', $circleaddmapping)->item (0);
		$node = $this->template->query ('tr/td[@id="circle_name"]', $circleinfoitem)->item (0);
		$node->nodeValue = htmlspecialchars ($CircleInfo[$this->CircleModel->nameRowName]);
		$node = $this->template->query ('tr/td[@id="Devices_Count"]', $circleinfoitem)->item (0);
		$Count = $this->DeviceToCircleModel->GetDevicesByCircleCount ($CircleInfo[$this->CircleModel->idRowName]);
		$node->nodeValue = htmlspecialchars ($Count);

		if ($Device_ID != '') {
			$node = $this->template->query ('table/tr/td/table/tr/td/input[@name="Device_ID"]', $circleaddmapping)->item (0);
			$node->setAttribute ('value', $Device_ID);
		}
		if ($StartDateTime != '') {
			$node = $this->template->query ('table/tr/td/table/tr/td/input[@name="StartDateTime"]', $circleaddmapping)->item (0);
			$node->setAttribute ('value', $StartDateTime);
		}
		if ($EndDateTime != '') {
			$node = $this->template->query ('table/tr/td/table/tr/td/input[@name="EndDateTime"]', $circleaddmapping)->item (0);
			$node->setAttribute ('value', $EndDateTime);
		}

		$this->template->content->appendChild ($circleaddmapping);
	}

	private function welcome($id){ 

		$data = array('To_Circle_ID'=>$id,'From_Circle_ID'=>1);  //定义参数  

		$data = http_build_query($data);  //把参数转换成URL数据 

		$opts = array('http'=>array('method'=>'POST', 'header'=>'Content-type: application/x-www-form-urlencoded', 'content'=>$data));

		$context  = stream_context_create($opts); 

		$sUrl = 'http://128.199.209.239/IM/index.php/Home/Message/welcome'; //此处必须为完整路径  

		$d = file_get_contents($sUrl,false,$context);
  	}

		//echo json_encode($data);

	private function addMappingPage () {

		
		if (array_key_exists ('id', $_REQUEST) && ctype_digit ($_REQUEST['id']) && ($CircleInfo = $this->CircleModel->CheckCircleItemExist ($_REQUEST['id'])) != NULL) {
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				if (ctype_digit ($_REQUEST['Device_ID']) && ($DeviceInfo = $this->DeviceModel->CheckDeviceItemExistByID ($_REQUEST['Device_ID'])) != NULL) {
					$DeviceToCircleInfo = $this->DeviceToCircleModel->GetCirclesByDevice ($_REQUEST['Device_ID']);
					if (count ($DeviceToCircleInfo) > 0) {
						if ($DeviceToCircleInfo[0][$this->DeviceToCircleModel->circleIDRowName] == $_REQUEST['id']) {
							$this->template->addWarningMesage ('Edit Successful');
							$this->DeviceToCircleModel->UpdateDeviceToCircle ($DeviceToCircleInfo[0][$this->DeviceToCircleModel->idRowName], $_REQUEST['Device_ID'], $_REQUEST['id'], $_REQUEST['StartDateTime'], $_REQUEST['EndDateTime']);
							$this->listPage ();
						} else {
							$this->template->addWarningMesage ('Device was maped');
//							$this->devicelistPage ();
							$this->NaddMappingPage ($CircleInfo, $_REQUEST['id'], $_REQUEST['Device_ID'], $_REQUEST['StartDateTime'], $_REQUEST['EndDateTime']);
						}
					} else {
						$this->welcome($_REQUEST['id']);
						$this->template->addWarningMesage ('Add Successful');
						$this->DeviceToCircleModel->AddDeviceToCircle ($_REQUEST['Device_ID'], $_REQUEST['id'], $_REQUEST['StartDateTime'], $_REQUEST['EndDateTime']);
						$this->listPage ();
					}
				} else {
					$this->template->addWarningMesage ('Device not exists');
					$this->NaddMappingPage ($CircleInfo, $_REQUEST['id'], $_REQUEST['Device_ID'], $_REQUEST['StartDateTime'], $_REQUEST['EndDateTime']);
				}
			} else {
				$this->NaddMappingPage ($CircleInfo, $_REQUEST['id']);
			}
		} else {
			$this->template->addWarningMesage ('no record here');
			$this->listPage ();
		}
	}


	private function listPage () {
		$page = 0;
		$totalpage = 0;
		$totalrows = $this->CircleModel->GetCircleCount ();

		if (array_key_exists ('page', $_REQUEST) && ctype_digit ($_REQUEST['page'])) {
			$page = $_REQUEST['page'];
		}
		$totalpage = ceil ($totalrows / $this->diaplayrows);
		if ($page != 0 && $totalpage <= $page) {
			$page = 0;
			$this->template->addWarningMesage ('no record here');
		}
		if ($totalpage == 0) {
			$totalpage = 1;
		}
		$circlelisttemplate = new template ();
		$circlelisttemplate->load ('html/CircleManagerlist.html');
		$circlelistform = $circlelisttemplate->dom->documentElement;
		$circlelistform = $this->template->dom->importNode ($circlelistform, true);

#		$node = $this->template->query ('div[@class="buttonarea"]/input[@id="addcircleButton"]', $circlelistform)->item (0);
#		$node->setAttribute ('onClick', sprintf ('javascript:relocation(\'?module=%s&action=add\');', $this->Loader->module));

//		$node = $this->template->query ('tbody[@id="circlelistitem"]', $circlelistform)->item (0);
		$node = $this->template->query ('table/tbody[@id="circlelistitem"]', $circlelistform)->item (0);
		$circlelist = $node->parentNode;
#		$circlelistitem = $node->cloneNode (true);
		$circlelistitem = $node;
		$circlelist->removeChild ($node);

		foreach ($this->CircleModel->GetCircleItems ($page * $this->diaplayrows, $this->diaplayrows) as $CircleItem) {
			$item = $circlelistitem->cloneNode (true);

			$node = $this->template->query ('tr/td[@id="circle_name"]', $item)->item (0);
			$node->nodeValue = htmlspecialchars ($CircleItem[$this->CircleModel->nameRowName]);

#			$node = $this->template->query ('tr/td[@id="pubDate"]', $item)->item (0);
#			$node->nodeValue = htmlspecialchars ($CircleItem[$this->CircleModel->typeRowName]);
#			$circlelist->appendChild ($item);

			$node = $this->template->query ('tr/td[@id="Devices_Count"]', $item)->item (0);
			$node->nodeValue = htmlspecialchars ($this->DeviceToCircleModel->GetDevicesByCircleCount ($CircleItem[$this->CircleModel->idRowName]));

			$node = $this->template->query ('tr/td[@id="Circle_Info"]/a', $item)->item (0);
			$node->setAttribute ('href', sprintf ('?module=%s&action=circleinfo&id=%d', $this->Loader->module, $CircleItem[$this->CircleModel->idRowName]));

			$circlelist->appendChild ($item);

		}

		$node = $this->template->query ('span[@id="totlepage"]', $circlelistform)->item (0);
		$node->nodeValue = htmlspecialchars ($totalpage);

		$node = $this->template->query ('span[@id="page"]', $circlelistform)->item (0);
		$node->nodeValue = htmlspecialchars ($page + 1);

		$node = $this->template->query ('a[@id="previouspage"]', $circlelistform)->item (0);
		if ($page == 0) {
			$node->setAttribute ('href', '#');
		} else {
			$node->setAttribute ('href', sprintf ('?module=%s&page=%d', $this->Loader->module, $page - 1));
		}
		$node = $this->template->query ('a[@id="nextpage"]', $circlelistform)->item (0);
		if ($page == $totalpage - 1) {
			$node->setAttribute ('href', '#');
		} else {
			$node->setAttribute ('href', sprintf ('?module=%s&page=%d', $this->Loader->module, $page + 1));
		}

		$this->template->content->appendChild ($circlelistform);

	}
}
?>
